<script lang="ts" setup>
import type { StateType } from './types';
import { reactive, onMounted,ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Page } from '@vben/common-ui';
import { Card, message } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
import { update_smart_car,get_smart_car } from '#/api/portal/rideSmart';
import { getArticle } from '#/api/portal/article';
import { $t } from '@vben/locales';
const route = useRoute();
const router = useRouter();
const routeMeta = router.currentRoute.value.meta;
const routeTitle = routeMeta.title.replace('管理', '');

const state: StateType = reactive({
  form: {
   
  },
  pageThemeFiles: [],
});

const carOptions = reactive<{ label: string; value: number }[]>([]);

const get_car = async () => {
  try {
    const res = await getArticle({ code: 'product',limt:99999 }); // 调接口
    if (res && res.data.list) {
      // 将接口返回的数据映射成 Select 可用格式
      carOptions.splice(0, carOptions.length, ...res.data.list.map((item: any) => ({
        label: item.post_title, // 显示文字
        value: item.id,    // 对应值
      })));
    }
  } catch (error) {
    console.error('获取下拉选项失败', error);
  }
};
let searchTimeout: any = null;

const searchArticles = async (keyword: string) => {
     const res = await getArticle({ keyword,code:'product' });
        carOptions.splice(0, carOptions.length, ...res.data.list.map((item: any) => ({
          label: item.post_title,
          value: item.id,
        })));

          BasicFormApi.updateSchema([
    {
      fieldName: 'articles',
      componentProps: {
        options: carOptions, // 这里传 reactive 数组
      },
    },
  ]);
        
};
// 表单初始化
const [BasicForm, BasicFormApi] = useVbenForm({
  handleSubmit: onSubmit,
  resetButtonOptions: { show: false },
  schema: [
        {
            component: 'Select',
               dependencies: {
                trigger: (values) => {
                  state.form.articles = values.options;
                  
                },
                // 随意一个字段改变时，都会触发
                triggerFields: [
                  'options',
                
                ],
              },

            componentProps: {
              allowClear: true,
              filterOption: false,
              options: carOptions,
              placeholder: $t('page.common.Please Enter'),
              mode: 'multiple',      // 多选
              showSearch: true,
                onSearch: (value: string) => {
                  searchArticles(value); // 输入时搜索
                },
              style: { width: '800px' }, // 设置宽度
            },
            fieldName: 'options',
            label: $t('page.common.selectVehicle'),
          },
  ],
});

// 获取页面初始数据
async function onGetPage() {
    const value = await get_smart_car();
    if(value.data){
          const res = await getArticle({ code:'product' ,limit:99999}); // 调接口
          if (res && res.data.list) {
            // 将接口返回的数据映射成 Select 可用格式
            carOptions.splice(0, carOptions.length, ...res.data.list.map((item: any) => ({
              label: item.post_title, // 显示文字
              value: item.id,    // 对应值
            })));
          }
          BasicFormApi.setFieldValue('options',value.data);
           BasicFormApi.setValues({ ...state.form });
    }
    
}

// 提交表单
async function onSubmit() {
  try {
    const values = { ...state.form }; // 确保是对象
    console.log(values.articles)
    const res = await update_smart_car({car:values.articles});

    message.success(res.msg);
  } catch (error) {
   
  }
}



// 页面加载时初始化
onMounted(async () => {
  await onGetPage();
});
</script>

<template>
  <Page>
    <Card :title="`${routeTitle} `+$t('page.common.Details')">
      <BasicForm />
    </Card>
  </Page>
</template>
